package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int
	//在线用户表
	OnlineMap map[string]*User
	maplock   sync.RWMutex

	//广播消息channel
	Message chan string
}

// 创建Server接口
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string), //广播消息channel
	}
	return server
}

// 监听广播msg 有信息就发出
func (this *Server) ListenMessager() {
	for {
		msg := <-this.Message
		this.maplock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.maplock.Unlock()
	}
}

func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	this.Message <- sendMsg

}
func (this *Server) Handler(conn net.Conn) {
	//当前链接的业务
	//todo
	user := NewUser(conn, this)
	fmt.Println("User:" + user.Name + "成功链接")
	//用户上线
	user.Online()

	isLive := make(chan bool)

	//接受客户端的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf) //从conn中read内容放入buf中 阻塞读
			if n == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("Conn Read err:", err)
				return
			}
			//提取用户消息（去除\n）
			msg := string(buf[:n-1])
			isLive <- true //用户发送了任意消息
			//用户处理msg
			user.DoMessage(msg)
			//this.BroadCast(user, msg)

		}
	}()

	for {
		select { //case后面的每个表达式都会被执行，但是case下面的内容不会
		case <-isLive:
			//donothing
		case <-time.After(time.Second * 60): //本质是一个channel 如果超时 After的channel便可读，若isLive进入了，便不会此处的case下的内容，但是case中的表达式会被执行
			//已经超时了
			//踢出该user
			user.SendMsg("Long Time No Action,You are Kicked out\n")
			//销毁链接
			close(user.C)
			//关闭链接
			conn.Close()
			//退出handle
			return //runtime.Goexit()
		}
	}

}

// 启动服务器
func (this *Server) Start() {
	//socket listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("net.Listen() error:", err)
		return
	}
	//close socket
	defer listener.Close()
	//启动监听器
	go this.ListenMessager()

	//新建协程池
	GoPool := NewPool(3)
	//accept
	go func() {
		for {
			conn, err := listener.Accept()
			if err != nil {
				fmt.Println("Listener.Accept() error:", err)
				continue
			}
			//将处理连接作为一个任务放入管道中
			t := NewTask(func() error { this.Handler(conn); return nil })
			GoPool.EntryChannel <- t

		}
	}()
	GoPool.run()

}
